require 'logger'
class Ability
  include CanCan::Ability

  #在controller中加入
  #   load_and_authorize_resource
  # or　控制器名与模型类名不同时
  #   load_and_authorize_resource :post
  # or 模型类存在命名空间时
  #   load_and_authorize_resource class: "Admin::User"
  #
  #但load_and_authorize_resource验证的并不只是RESTful的７个action,任意action都可以，
  #　example:
  #   def discontinue
  #     #Automatically does the following:
  #     #@product = Product.find(params[:id])
  #     #authorize! :discontinue, @product
  #   end
  #如上所说，show动作需要show权限，其他的动作原理相同


  def initialize(user,options= {})
    # Define abilities for the passed in user here. For example:
    #
      user ||= Admin::User.new # guest user (not logged in)
      alias_action :create, :destroy, :update, :read, :to => :crud
      alias_action :create,  :to => :tourist
      can :crud, Admin::User

      #关闭注册功能
      # unless !options[:close_registration].nil? && options[:close_registration]== true
      #   can :registration, Admin::User
      # end
      # unless !options[:close_login_function].nil? && options[:close_login_function]== true
      #   can :login_function, Admin::User
      # end
      #
      #
      # if user.has_role?(:admin) && user.has_role?(:manage)
      #   can :manage, :all
      # end
      # if  user.has_role? :ordinary
      #   can [:update], Admin::User, :id => user.id
      # end

    #can :registration, Admin::User
    #
    # can :manage, :all 表示赋予所有的资源以manage的权限，即所有
    # can :update, Admin::User 表示赋予User类update的权限

      #如果没有登录则默认使用游客的账号权限
      if user.empty?
        user = Admin::User.find_by_email("tourist@163.com")
      end
        user.permissions.each do |permission|
          #查询出来的对象的字段只能用empty判断是否为'',因为其默认就为'',nil查询没有任何意义
          if permission.subject_class=='all'
            can permission.permission_action.action_name.to_sym, :all
          elsif permission.subject_id.blank?
            can permission.permission_action.action_name.to_sym, permission.subject_class.to_s.camelize.constantize
          elsif permission.subject_id.present?
            can permission.permission_action.action_name.to_sym, permission.subject_class.to_s.camelize.constantize, id: subject_id

          end
        end

    #获取当前用户下的所有的角色
  end





end
